package com.blb.zy_community.service.impl;

import com.alibaba.fastjson.JSON;
import com.blb.zy_community.entity.SysDept;
import com.blb.zy_community.mapper.SysDeptMapper;
import com.blb.zy_community.service.ISysDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author 二组
 * @since 2023-06-18
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public List<SysDept> selectChildDeptTreeByParentId(Long parentId) {
        return sysDeptMapper.selectChildDeptTreeByParentId(parentId);
    }

    @Override
    public List<SysDept> FindDept(Long parentId, String deptName, String status) {
        return sysDeptMapper.selectByDept(parentId,deptName,status);
    }

    @Override
    public List<SysDept> filterByDeptAndStatus(List<SysDept> sysDepts, String deptName, String status) {
        List<SysDept> newSysDepts = new ArrayList<>();
        System.out.println("原本的");
        String s1 = JSON.toJSONString(sysDepts);
        System.out.println(s1);

        getChildrenNode(sysDepts,newSysDepts,deptName,status);

//        删除对于的子树
        uniqueSysDeptTree(newSysDepts,new ArrayList<Long>());


//        System.out.println("筛选后的");
//        String s = JSON.toJSONString(newSysDepts);
//        System.out.println(s);

        return newSysDepts;
    }



    public void getChildrenNode(List<SysDept> sysDepts,List<SysDept> newSysDepts, String deptName, String status){

        Iterator<SysDept> iterator = sysDepts.iterator();
        while (iterator.hasNext()){
            SysDept sysDept = iterator.next();

            if (sysDept.getDeptName().contains(deptName)&&sysDept.getStatus().equals(status)){
                newSysDepts.add(sysDept);
            }
            if (sysDept.getChildDept()!=null){
                System.out.println("递归");
                System.out.println(sysDept.getDeptName());
                getChildrenNode(sysDept.getChildDept(),newSysDepts,deptName,status);
            }

            if (!sysDept.getDeptName().contains(deptName)||!sysDept.getStatus().equals(status)){
                iterator.remove();
            }
        }


    }
//    去重
    private void uniqueSysDeptTree(List<SysDept> newSysDepts,List<Long> ids) {

        Iterator<SysDept> sysDeptIterator = newSysDepts.iterator();
        while (sysDeptIterator.hasNext()){
            SysDept sysDept = sysDeptIterator.next();
            uniqueSysDeptTree(sysDept.getChildDept(),ids);
            if (ids.contains(sysDept.getDeptId())){
                sysDeptIterator.remove();
            }else {
                ids.add(sysDept.getDeptId());
            }
        }
    }




}
